layui.use(['table', 'admin', 'ax', 'func', 'layer'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var layer = layui.layer;
    /**
     * 目录服务管理
     */
    var DbServicelist = {
        tableId: "dbServicelistTable"
    };

    /**
     * 初始化表格的列
     */
    DbServicelist.initColumn = function () {
        return [[
            {type: 'checkbox', title: '全选'},
            {field: 'id', align: 'center', hide: true, title: 'id'},
            {field: 'department', sort: false, title: '部门', hide: true, align: 'center'},
            {field: 'dbName', sort: false, title: '数据库', align: 'center'},
            {field: 'userId', sort: false, title: '用户id', hide: true, align: 'center'},
            {field: 'username', sort: false, title: '账号', hide: true, align: 'center'},
            {field: 'password', sort: false, title: '密码', hide: true, align: 'center'},
            {field: 'dbUrl', sort: false, title: '账号', hide: true, align: 'center'},
            {field: 'dbNumber', sort: false, title: '密码', hide: true, align: 'center'},
            {
                field: 'servicetype', sort: false, align: 'center', title: '服务类型', templet: function (res) {
                    if (res.servicetype == '1') {
                        return '数据库服务'
                    }
                }
            },
            {field: 'system', sort: false, align: 'center', title: '应用系统'},
            {
                field: 'open', sort: false, title: '是否公开', align: 'center', templet: function (res) {
                    if (res.open == '1') {
                        return '是'
                    } else {
                        return '否'
                    }
                }
            },
            {
                field: 'state', sort: false, title: '状态', align: 'center', templet: function (res) {
                    if (res.state == '1') {
                        return '启动'
                    } else {
                        return '停止'
                    }
                }
            },
            {
                field: 'spState', sort: false, title: '审批情况', hide: false, align: 'center', templet: function (res) {
                    if (res.spState == 0) {
                        return "<span style='color: grey'>审批中<span>"
                    }
                    if (res.spState == 1) {
                        return "<span style='color: #00B83F'>审批通过</span>"
                    }
                    if (res.spState == 2) {
                        return "<span style='color: red'>被驳回</span>"
                    }
                }
            },
            {field: 'details', sort: false, title: '说明', align: 'center'},
            {field: 'standard', sort: false, title: '使用规范', align: 'center', hide: false},
            {
                field: 'effectiveTime',
                sort: false,
                event: 'addTime',
                align: 'center',
                title: '有效期至',
                templet: function (res) {
                    var now = new Date().getTime();
                    var dateTime = now - res.effectiveTime;
                    var newdata = new Date(parseInt(res.effectiveTime));
                    var commonTime = format(newdata);
                    var weektime = -3600 * 1000 * 24 * 7;
                    var daytime = -3600 * 1000 * 24;
                    var yeartime = -3600 * 1000 * 24 * 3650;
                    if (dateTime < daytime && dateTime > weektime) {
                        return '<span style="color: #ff8000;">' + commonTime + '</span>';
                    } else if (dateTime < yeartime) {
                        return '<span >永久</span>';
                    } else if (dateTime < 0) {
                        return '<span >' + commonTime + '</span>';
                    } else {
                        return '<span style="color: red;">' + commonTime + '</span>';
                    }
                }
            },
            {field: 'remarks', sort: false, title: '备注', hide: true, align: 'center'},
            {field: 'revision', sort: false, title: '乐观锁', hide: true, align: 'center'},
            {field: 'createdBy', sort: false, title: '创建人', hide: true, align: 'center'},
            {field: 'createdTime', sort: false, title: '创建时间', hide: true, align: 'center'},
            {field: 'updatedBy', sort: false, title: '更新人', hide: true, align: 'center'},
            {field: 'updatedTime', sort: false, title: '更新时间', hide: true, align: 'center'},
            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    DbServicelist.search = function () {
        var queryData = {};

        queryData['dbName'] = $('#dbName').val();
        queryData['servicetype'] = $('#servicetype').val();
        queryData['system'] = $('#system').val();
        queryData['state'] = $('#state').val();
        queryData['open'] = $('#open').val();

        table.reload(DbServicelist.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加对话框
     */
    // DbServicelist.openAddDlg = function () {
    //     func.open({
    //         title: '',
    //         content: Feng.ctxPath + '/databaseListKh/add',
    //         tableId: DbServicelist.tableId
    //     });
    // };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    DbServicelist.openEditDlg = function (data) {
        func.open({
            title: '',
            content: Feng.ctxPath + '/databaseListKh/edit?id=' + data.id,
            tableId: DbServicelist.tableId
        });
    };


    /**
     * 查看详情
     * @param data
     */
    DbServicelist.onDetails = function (data) {
        // console.log(data)
        window.location.href = Feng.ctxPath + '/databaseListKh/Details?id=' + data.id
    }


    // 渲染表格
    var tableResult = table.render({
        elem: '#' + DbServicelist.tableId,
        url: Feng.ctxPath + '/databaseListKh/list',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        skin: 'line',
        even: false,
        cols: DbServicelist.initColumn(),
        done: function () {
            $('tr').css('background-color', '#ffffff');
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        DbServicelist.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

        // DbServicelist.openAddDlg();
        // window.location.href = Feng.ctxPath + '/databaseListKh/exchangeComputer'
        window.location.href = Feng.ctxPath + '/databaseListKh/add'
    });
    // 发布服务
    $('#btnRel').click(function () {
        var checkStatus = table.checkStatus('dbServicelistTable'),
            data = checkStatus.data;
        console.log(data)
        if (data.length != 1) {
            Feng.error("请选择一个哦")
            return
        }
        //发布服务之前有一个弹窗
        layer.open({
            type: 1,
            title: ['发布服务申请', 'font-size:16px;text-align:center;padding: 0 0 0 0'],
            closeBtn: false,
            area: ['400px', '250px'],
            shade: 0.6,
            id: "",
            btn: ['确定', '取消'],
            btnAlign: 'c',
            moveType: 0,
            content: '<div class="layui-row" style="padding:65px 0 0 0"><div class="layui-col-md10 layui-col-md-offset1"><span style="font-size: 16px">是否同意将&nbsp;"' + data[0].dbName + '"&nbsp;数据库发布到大数据仓库平台目录' + '</span></div></div>',
            success: function (layero) {
                var btn = layero.find('.layui-layer-btn');
                btn.find('.layui-layer-btn0').click(function () {
                    //获取选中数据
                    var btnName = 'btnRel';
                    DbServicelist.btnsEdit(data[0], btnName);
                })
            }
        })
    });
    // 申请升级
    //TODO 申请升级需要完善

    // $('#btnApp').click(function () {
    //     //获取选中数据
    //     var checkStatus = table.checkStatus('dbServicelistTable'),
    //         data = checkStatus.data;
    //     if (data.length != 1) {
    //         Feng.error("请选择一个哦")
    //         return
    //     } else {
    //         admin.open({
    //             type: 2,
    //             title: '',
    //             area: ['700px', '480px'],
    //             content: Feng.ctxPath + '/dbServicedetails/add?serviceId=' + Feng.getUrlParam("id"),
    //             tableId: DbServicelist.tableId,
    //             end: function () {
    //                 table.reload(DbServicelist.tableId);
    //             }
    //         });
    //     }
    // });
    // 启动
    $('#btnStar').click(function () {
        //获取选中数据
        var checkStatus = table.checkStatus('dbServicelistTable'),
            data = checkStatus.data;
        if (data.length != 1) {
            Feng.error("请选择一个哦")
            return
        }
        if (data[0].open != 1){
            Feng.error("请先发布服务")
            return;
        }
        var btnName = 'btnStar';
        DbServicelist.btnsEdit(data[0], btnName);

    });
    // 停止
    $('#btnStop').click(function () {
        //获取选中数据
        var checkStatus = table.checkStatus('dbServicelistTable'),
            data = checkStatus.data;
        if (data.length != 1) {
            Feng.error("请选择一个哦")
            return
        }
        if (data[0].open != 1){
            Feng.error("请先发布服务")
            return;
        }
        var btnName = 'btnStop';
        DbServicelist.btnsEdit(data[0], btnName);
    });
    // 废弃
    $('#btnKil').click(function () {
        //获取选中数据
        var checkStatus = table.checkStatus('dbServicelistTable'),
            data = checkStatus.data;
        if (data.length != 1) {
            Feng.error("请选择一个哦")
            return
        }

        var btnName = 'btnKil';
        DbServicelist.btnsEdit(data[0], btnName);
    });
    /**
     * 修改启动升级等操作
     */
    DbServicelist.btnsEdit = function (data, btnName) {
        console.log(data, btnName)
        if (btnName == 'btnRel') {
            data.open = 1;
        } else if (btnName == 'btnStar') {
            data.state = 1;
        } else if (btnName == 'btnStop') {
            data.state = 0;
        } else if (btnName == 'btnKil') {
            data.state = '2_kil';
        }
        var ajax = new $ax(Feng.ctxPath + "/databaseListKh/editItem", function (data) {
            Feng.success("更新成功！");
            table.reload(DbServicelist.tableId);
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
        ajax.set(data);
        ajax.start();

    };


    // 工具条点击事件
    table.on('tool(' + DbServicelist.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            DbServicelist.openEditDlg(data);
        } else if (layEvent === 'delete') {
            DbServicelist.onDeleteItem(data);
        } else if (layEvent == 'addTime') {
            layer.open({
                type: 2,
                area: ["500px", "400px"],
                fixed: false,
                offset: "35px",
                resize: false,
                shade: 0.1,
                skin: "layui-layer-admin",
                title: '增加' + data.dbName + '数据库有效期',
                content: Feng.ctxPath + '/databaseListKh/addDataTime?id=' + data.id + '&effectiveTime=' + data.effectiveTime,  // 注意这里有.html()
                end: function () {
                    table.reload(DbServicelist.tableId);
                }
            });
        } else if (layEvent == 'Details') {
            DbServicelist.onDetails(data);
        }
    });

    function format(f) {
        return f.getFullYear() + "-" + (f.getMonth() + 1) + "-" + f.getDate();
        // + "日 " + f.getHours() + "点" + f.getMinutes() + "分" + f.getSeconds() + "秒"
    }
});
